package cn.wolfcode.luowowo.website.web.Interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.web.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.web.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录检查
 */
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //根据游览器发送请求做拦截,首先判断用户有没有登录,如果有登录那么就直接放行
        //先拿cookie,在从redis中通过key拿到登录的对象
        //细节:并不是所有请求都要登录才可以访问,那么就需要自定义注解,用来标记哪些方法需要登录,哪些不需要
        UserInfo user = null;
        String token = CookieUtil.getToken(request, response);
        if (token != null) {
            user = userInfoRedisService.getUserByToken(token);
        }
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //判断当前请求的方法有没有贴这个注解,如果贴了注解就表示一定要登录才能访问
            if (hm.hasMethodAnnotation(RequireLogin.class)) {
                if (user == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        //表示登录了那么把当前用户的信息放到session中
        request.getSession().setAttribute("userInfo", user);
        return true;
    }
}
